/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.gui.wizard;

import java.io.File;
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bugstat.common.TimeInterval;
import org.bugstat.common.TimeStep;
import org.bugstat.common.reports.Report;
import org.bugstat.common.utils.FractionedProgressListener;
import org.bugstat.common.utils.ProgressListener;
import org.bugstat.exporters.BugExporer;
import org.bugstat.exporters.BugExportersManager;
import org.bugstat.exporters.BugInfoReader;
import org.bugstat.exporters.ConnectionManager;
import org.bugstat.exporters.ConnectionManager.DatabaseType;
import org.bugstat.exporters.StorageManager;
import org.bugstat.generators.GeneratorManager;
import org.bugstat.generators.ReportGenerator;
import org.bugstat.gui.ApplicationDataLocator;
import org.bugstat.gui.UIStrings;
import org.bugstat.renderers.RendererManager;
import org.bugstat.renderers.ReportInformation;
import org.pietschy.wizard.WizardStep;
import org.pietschy.wizard.models.StaticModel;

/**
 * This is wizard model for export/generate process
 * 
 * @author Basil Shikin
 */
public class BugstartReportWizardModel
    extends StaticModel
{
    private static Log log = LogFactory.getLog( BugstartReportWizardModel.class );
    
    private final SelectTrackingSystemPage   selectTrackingSystemPage;
    private final SelectExportPropertiesPage selectExportPropertiesPage;
    private final SelectImportantDatesPage   selectImportantDatesPage;
    private final SelectOutputPropertiesPage selectOutputPropertiesPage;
    private final ProgressPage               progressPage;
    private final FinishedPage               finishedPage;

    boolean isDatabaseConnected = false;
    Properties databaseProperties  = null;
    StorageManager storageManager = null;
    BugExporer exporter = null;
    
    public BugstartReportWizardModel()
    {
        selectTrackingSystemPage = new SelectTrackingSystemPage();
        selectExportPropertiesPage = new SelectExportPropertiesPage();
        selectImportantDatesPage = new SelectImportantDatesPage();
        selectOutputPropertiesPage = new SelectOutputPropertiesPage();;
        
        progressPage  = new ProgressPage();
        finishedPage  = new FinishedPage();
        
        add( selectTrackingSystemPage );
        add( selectExportPropertiesPage );
        add( selectImportantDatesPage );
        add( selectOutputPropertiesPage );
        add( progressPage );
        add( finishedPage );
        
        setLastVisible( false );
    }
    
    /**
     * Initialize current model
     */
    public void initialize() throws Exception
    {
        log.debug("Initializing wizard manager..." );
        
        final File baseFolder = new File( ApplicationDataLocator.getCacheFolder(), selectTrackingSystemPage.getDatabaseName() );
        storageManager = new StorageManager( baseFolder );
        
        selectTrackingSystemPage.setExporters( BugExportersManager.listExporters() );
        selectTrackingSystemPage.setDatabaseTypes( ConnectionManager.getSupportedDatabaseTypes() );
        
        selectExportPropertiesPage.setReportGenerators( GeneratorManager.listGenerators() );

        selectOutputPropertiesPage.setReportRenderers( RendererManager.listRenderers() );
        
        log.debug("Wizard manager initialized" );
    }
    
    @Override
    public boolean isLastStep(WizardStep step)
    {
        return step == finishedPage;
    }

    @Override
    public boolean isLastAvailable()
    {
        return getActiveStep() == finishedPage;
    }

    @Override
    public boolean isPreviousAvailable()
    {
        return super.isPreviousAvailable() &&
               getActiveStep() != finishedPage &&
               getActiveStep() != progressPage;
    }
    
    
    @Override
    protected void setActiveStep(WizardStep activeStep)
    {
        super.setActiveStep(activeStep);
        
        if ( activeStep == progressPage )
        {
            runGenerationProcess();
        }
    }
    
    @Override
    public void nextStep()
    {
        final WizardStep currentStep = getActiveStep();
        
        
        // If we are on select bug tracker page
        if ( currentStep == selectTrackingSystemPage && !isDatabaseConnected )
        {
            // Do not go to the next page, connect to bug tracking system
            connectToBugTracker();
        }        
        else
        {
            super.nextStep();
        }
    }

    private void connectToBugTracker()
    {
        new Thread("generate_bug_report") {
            @Override
            public void run()
            {
                selectTrackingSystemPage.setBusy( true );
                
                exporter = selectTrackingSystemPage.getSelectedExporter(); 
                
                final DatabaseType databaseType = selectTrackingSystemPage.getDatabaseType();
                
                databaseProperties = new Properties();
                databaseProperties.setProperty( ConnectionManager.KEY_DATABASE, selectTrackingSystemPage.getDatabaseName() );
                databaseProperties.setProperty( ConnectionManager.KEY_HOST, selectTrackingSystemPage.getDatabaseHostname() );
                databaseProperties.setProperty( ConnectionManager.KEY_PORT, selectTrackingSystemPage.getDatabasePort() );
                databaseProperties.setProperty( ConnectionManager.KEY_USERNAME, selectTrackingSystemPage.getDatabaseUsername() );
                databaseProperties.setProperty( ConnectionManager.KEY_PASSWORD, selectTrackingSystemPage.getDatabasePassword() );
                                
                try
                {
                    final ConnectionManager connectionManager = new ConnectionManager( databaseType, databaseProperties);
                    connectionManager.ensureCanConnect();
                    
                    // Initialize exporter
                    exporter.setManagers( connectionManager, storageManager );
                    
                    selectExportPropertiesPage.setFirstBugDate( exporter.retrieveFirstBugDate() );
                    isDatabaseConnected = true;
                    
                    nextStep();
                }
                catch (Throwable e)
                {
                    log.error("Unable to connect to bug tracker", e );
                    
                    final String errorMessage = MessageFormat.format( UIStrings.TEXT_CANT_CONNECT_TO_DATABASE , selectTrackingSystemPage.getDatabaseName(), selectTrackingSystemPage.getDatabaseHostname(), e.getMessage() );
                    selectTrackingSystemPage.setErrorMessage( errorMessage );
                }
                finally
                {
                    selectTrackingSystemPage.setBusy( false );
                }
            }
            
        }.start();
    }
    
    private String retrieveReportName()
    {
        return exporter.getBugTrackerName() + " " + UIStrings.TEXT_REPORT;
    }
    
    private void runGenerationProcess()
    {
        progressPage.setBusy( true );
        
        new Thread("generate_bug_report") {
            @Override
            public void run()
            {
                final long before = System.currentTimeMillis();
                log.info("Generating bug reports...");
                
                try
                {
                    final ProgressListener progressListener = new FractionedProgressListener( progressPage.getProgressListener(), 3 );
                    
                    final TimeInterval timeInterval = new TimeInterval( exporter.retrieveFirstBugDate(), TimeStep.WEEK );
                    
                    final ReportInformation reportInformation = new ReportInformation( retrieveReportName(),
                                                                                       timeInterval,
                                                                                       selectImportantDatesPage.getImportantDates() );
                    
                    // EXPORT BUGS
                    exporter.exportBugs( timeInterval, progressListener );
                    
                    // GENERATE REPORTS
                    final BugInfoReader reader = new BugInfoReader( storageManager.getLocation() );
                    reader.initializeReader();
                    
                    final GeneratorManager generatorManager = new GeneratorManager( reader );
                    final List<ReportGenerator> generators = selectExportPropertiesPage.getSelectedGenerators();
                    final List<Report> reports = generatorManager.generateReports( timeInterval, generators, progressListener);
                    
                    // RENDER REPORTS
                    final File outputFolder = new File( selectOutputPropertiesPage.getSelectedOutputFolder() );
                    final RendererManager rendererManager = new RendererManager();
                    rendererManager.renderReports( reports, reportInformation, outputFolder, selectOutputPropertiesPage.getSelectedRenderers(), progressListener);
                    
                    final long after = System.currentTimeMillis();
                    log.info("Bug reports generated in " + ( after - before ) + "ms");
                    
                    finishedPage.setCompletedText( MessageFormat.format( UIStrings.TEXT_REPORTS_CREATED_DETAILS, outputFolder.getAbsolutePath() ) );
                }
                catch (Exception e)
                {
                    final long after = System.currentTimeMillis();
                    log.error( "Unable to generate reports (failure after " + ( after - before ) + "ms)", e );
                    
                    // TODO HANDLE ERROR
                }
                finally
                {
                    progressPage.setBusy( false );
                    nextStep();
                }
            }
            
        }.start();
    }
}
